﻿using System;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;

namespace Plasp.WebScoketServer.Web.WebSocketProvider
{
    public class WebSocketHandler
    {
        public readonly ConnectionManager ConnectionManager;
        public WebSocketHandler(ConnectionManager connectionManager) {
            ConnectionManager = connectionManager;
        }

        /// <summary>
        /// 传进一个实例
        /// </summary>
        /// <param name="socket"></param>
        /// <returns></returns>
        public async Task OnConnected(WebSocket socket) {
            await Task.Run(() => ConnectionManager.AddWebSocket(socket));
        }

        /// <summary>
        /// 断开一个连接
        /// </summary>
        /// <param name="socket"></param>
        /// <returns></returns>
        public async Task OnDisConnected(WebSocket socket)
        {
            await ConnectionManager.RemoveSocketAsync(ConnectionManager.GetKey(socket));
        }

        /// <summary>
        /// 接收一个请求进来，传出响应
        /// </summary>
        /// <returns></returns>
        public async Task HandlerProcessAsync(WebSocket socket) {
            //移除断开连接的socket对象
            await ConnectionManager.RemoveUnConnected();

            WebSocketReceiveResult result;
            do {
                var m_result = new byte[1024 * 8];
                var buffer = new ArraySegment<byte>(m_result);
                result = await socket.ReceiveAsync(buffer, CancellationToken.None);
                //TODO 处理用户发送数据
            } while (result.EndOfMessage);
        }
    }
}
